﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using GTasksPlus.Code;
using GTasksPlus.ViewModels;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;

namespace GTasksPlus.Views
{
    public partial class TaskView
    {
        public static string Id = String.Empty;
        public static string name = String.Empty;

        public TaskView()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!IsLoggedIn())
            {
                NavigationService.Navigate(new Uri("/Login.xaml", UriKind.RelativeOrAbsolute));
            }
            else
            {
                ApplicationTitle.Text = GTasksSettings.ApplicationTitle;
                if (NavigationContext.QueryString.ContainsKey("Id"))
                    Id = NavigationContext.QueryString["Id"];

                if (!string.IsNullOrEmpty(Id))
                {
                    var itemViewModel = new TaskViewModel(Id);
                    DataContext = itemViewModel;
                    AddPinButton();
                }
                else
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
                }
            }
        }

        private void AddPinButton()
        {
            var tile = ShellTile.ActiveTiles.FirstOrDefault(o => o.NavigationUri.ToString().Contains(Id));
            ApplicationBarIconButton pinButton;
            if (tile == null)
                pinButton = new ApplicationBarIconButton { Text = "Pin to Start", IconUri = new Uri("/Images/pin.png", UriKind.Relative) };
            else
                pinButton = new ApplicationBarIconButton { Text = "Unpin", IconUri = new Uri("/Images/unpin.png", UriKind.Relative) };
            pinButton.Click -= Pin_Click;
            pinButton.Click += Pin_Click;
            if (ApplicationBar.Buttons.Count < 4)
                ApplicationBar.Buttons.Add(pinButton);
        }

        #region Event Handlers

        private void Add_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Manipulate.xaml?Id=new&List=" + Id, UriKind.RelativeOrAbsolute));
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            var itemViewModel = new TaskViewModel(Id);
            DataContext = itemViewModel;
        }

        private void Logout_Click(object sender, EventArgs e)
        {
            Logout();
            while (NavigationService.CanGoBack)
                NavigationService.RemoveBackEntry();
            NavigationService.Navigate(new Uri("/Login.xaml", UriKind.RelativeOrAbsolute));
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            while (NavigationService.CanGoBack)
                NavigationService.RemoveBackEntry();
            if (!NavigationService.Source.ToString().Contains("From=Tile"))
            {
                e.Cancel = true;
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }

        /// <summary>
        /// Toggle pinning a Tile for this page on the Start screen.
        /// </summary>
        private void Pin_Click(object sender, EventArgs eventArgs)
        {
            // Try to find a Tile that has this page's URI.
            var tile = ShellTile.ActiveTiles.FirstOrDefault(o => o.NavigationUri.ToString().Contains(Id));

            if (tile == null)
            {
                // No Tile was found, so add one for this page.
                var tileData = new StandardTileData { Title = PageTitle.Text, BackgroundImage = new Uri("/Images/JustTick173.png", UriKind.Relative) };
                ShellTile.Create(new Uri(("/Views/TaskView.xaml?Id=" + Id + "&From=Tile"), UriKind.Relative), tileData);
                //Uri.EscapeUriString
            }
            else
            {
                // A Tile was found, so remove it.
                tile.Delete();
            }

            ApplicationBar.Buttons.Remove(sender);
            AddPinButton();
        }

        private void EmailTasks_Click(object sender, EventArgs eventArgs)
        {
            string taskBody = String.Empty;
            var tasks = (TaskViewModel)DataContext;
            foreach (var task in tasks.TaskItem)
            {
                if (!string.IsNullOrEmpty(task.title))
                {
                    taskBody += String.Format("{0}) {1}\n", tasks.TaskItem.IndexOf(task) + 1, task.title);
                    if (!string.IsNullOrEmpty(task.notes))
                        taskBody += string.Format("\t{0}\n", task.notes);
                }
            }
            var emailComposeTask = new EmailComposeTask
                                       {
                                           Body = taskBody,
                                           Subject = "Emailing Tasks - " + PageTitle.Text
                                       };
            if (!string.IsNullOrEmpty(taskBody))
                emailComposeTask.Show();
        }

        private void CheckBox_Tap(object sender, RoutedEventArgs e)
        {
            var currentItem = e.OriginalSource as CheckBox;
            if (currentItem != null)
            {
                var parentListId = ((TaskViewModel)DataContext).ParentList.id;
                var currentId = currentItem.Tag.ToString();
                bool isChecked = currentItem.IsChecked != null && (bool)currentItem.IsChecked;
                TaskHelper.UpdateTaskStatus(parentListId, currentId, isChecked, Response);
            }
        }

        private void Response(bool obj)
        {
        }

        private void Textblock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var currentItem = e.OriginalSource as TextBlock;
            if (currentItem != null)
            {
                //Uri.EscapeUriString
                NavigationService.Navigate(new Uri(("/Views/Manipulate.xaml?Id=" + currentItem.Tag + "&List=" + Id), UriKind.RelativeOrAbsolute));
            }
        }

        #endregion

        private void CheckBox_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var checkBox = sender as CheckBox;
            if (checkBox == null)
                return;

            //var refreshButton = ApplicationBar.Buttons[1] as ApplicationBarIconButton;
            //if (refreshButton != null)
            //    refreshButton.IsEnabled = (sender as CheckBox).IsEnabled;

            var emailButton = ApplicationBar.Buttons[2] as ApplicationBarIconButton;
            if (emailButton != null)
                emailButton.IsEnabled = (sender as CheckBox).IsEnabled;
        }

        private void Completed_Click(object sender, EventArgs e)
        {
            TaskHelper.ClearCompletedTasks(Id, RefreshTaskList);
        }

        private void RefreshTaskList(bool obj)
        {
            if (obj)
                DataContext = new TaskViewModel(Id);
        }
    }
}